package org.itboys.member.service;

import com.google.common.collect.Maps;
import org.apache.commons.lang.StringUtils;
import org.itboys.commons.utils.encryption.Digests;
import org.itboys.commons.utils.io.FileUtils;
import org.itboys.framework.resource.ResourceHolder;
import org.itboys.member.dto.MemberDTO;
import org.itboys.member.entity.Member;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseService;
import org.itboys.mongodb.utils.page.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 会员
 * @author weisky
 *
 */
@Service
public class MemberService extends BaseService<Member, Long>{

	private static final long serialVersionUID = 1L;

	@Resource(name = "memberDS")
	private MongoDataSource ds;
	@Autowired
	private ResourceHolder resourceHolder;

	@Override
	protected MongoDataSource getMongoDataSource() {
		return ds;
	}

	/**
	 * 根据unionId获取会员信息
	 * @param unionId
	 * @return
	 */
	public Member findByUnionId(String unionId){
		return getByField("thirdObjId", unionId);
	}

	/**
	 * 我的粉丝 不带分页
	 * @param memberId
	 * @param  level 0-所有粉丝 1-3第几级粉丝
	 * @return
	 */
	public List<Member> myThreeTeam(Long memberId, int level, String name){
		try{
			Member member = super.getById(memberId);
			Map<String, Object> param = Maps.newHashMapWithExpectedSize(4);
			param.put("contains:path", member.getPath());
			if(StringUtils.isNotBlank(name)) {
				param.put("contains:nickname", name);
			}
			if(level > 0){
				param.put("level",member.getLevel() + level);
			}else{//level==0 表示获取我的所有成员
				param.put("level >= ", member.getLevel());
				param.put("level <= ", member.getLevel() + 3);
			}
			return super.list(param);
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}

	public List<Member> myThreeTeam(Long memberId, int level, int pageNo, int pageSize){
		try{
			Member member = super.getById(memberId);
			Map<String, Object> param = Maps.newHashMapWithExpectedSize(4);
			param.put("pageNo", pageNo);
			param.put("pageSize", pageSize);
			param.put("contains:path", member.getPath());
			if(level > 0){
				param.put("level",member.getLevel() + level);
			}else{//level==0 表示获取我的所有成员
				param.put("level >= ", member.getLevel());
				param.put("level <= ", member.getLevel() + 3);
			}
			return super.page(param).getData();
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 带有分页的查询我的粉丝
	 * @param memberId
	 * @param level
	 * @param pageNo
	 * @param pageSize
	 * @return
	 */
	public Page<Member> myThreeTeamPage(Long memberId, int level, int pageNo, int pageSize){
		try{
			Member member = super.getById(memberId);
			Map<String, Object> param = Maps.newHashMapWithExpectedSize(4);
			param.put("pageNo", pageNo);
			param.put("pageSize", pageSize);
			param.put("contains:path", member.getPath());
			if(level > 0){
				param.put("level",member.getLevel() + level);
			}else{//level==0 表示获取我的所有成员
				param.put("level >= ", member.getLevel());
				param.put("level <= ", member.getLevel() + 3);
			}
			return super.page(param);
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 修改或者保存
	 * @param member
	 * @param logos : 头像
	 * @return -1:账号已存在  0：系统错误  1：成功
	 */
	public int insert(Member member, MultipartFile logos){
		try{

			String logo = null;
			if(logos != null && !logos.isEmpty()){
				logo = FileUtils.saveFile(logos.getInputStream(), resourceHolder.getStringValue("fileUploadPath"), logos.getOriginalFilename(), logos.getContentType());
			}

			if(member.getId() != 0){//修改
				Member mm = super.getById(member.getId());
				if(StringUtils.isNotBlank(logo)){
					member.setLogo(logo);
				}else{
					member.setLogo(mm.getLogo());
				}
				member.setPassword(mm.getPassword());
				member.setType(mm.getType());
				member.setLevel(mm.getLevel());
				member.setStatus(mm.getStatus());
				update(member);
			}else{//新增
				boolean exist = super.exists("username", member.getUsername());//判断手机号是否已经被注册过了
				if(exist){
					return -1;//手机号（用户名）已存在
				}
				member.setPassword(Digests.md5(member.getPassword()));//将密码转换成MD5加密
				member.setLogo(logo);
				save(member);
			}
			return 1;
		}catch(Exception e){
			e.printStackTrace();
			logger.error("MemberService.insert error", e);
			return 0;
		}
	}

	/**
	 * 用于微信的保存
	 * @param member
	 * @return
	 */
	public boolean weixinInsert(Member member){
		try{
			member.setPassword(Digests.md5(member.getPassword()));//将密码转换成MD5加密
			save(member);
			return true;
		}catch(Exception e){
			e.printStackTrace();
			logger.error("MemberService.weixinInsert error", e);
			return false;
		}
	}

	/**
	 * 修改会员状态
	 * @param memberId
	 * @param status
	 * @return
	 */
	public boolean updateStatus(Long memberId, int status){
		try{
			super.update(memberId, "status", status);
			return true;
		}catch(Exception e){
			e.printStackTrace();
			logger.error("MemberService.updateStatus error", e);
			return false;
		}
	}

	/**
	 * 修改密码
	 * @param oldPwd
	 * @param newPwd
	 * @return
	 */
	public int updatePwd(String mobile, String oldPwd, String newPwd){
		try{
			Member member = super.getByField("username", mobile);
			if(member != null){
				if(!StringUtils.equals(Digests.md5(oldPwd), member.getPassword())){//旧密码跟新密码不相同
					return -2;
				}
				super.update(member.getId(), "password", Digests.md5(newPwd));
				return 1;//修改成功
			}
			return -1;//会员不存在
		}catch(Exception e){
			logger.error("MemberService.updatePwd error", e);
			return 0;
		}
	}

	/**
	 * 修改密码
	 * @param mobile
	 * @param newPwd
	 * @return
	 */
	public int updatePwd(String mobile, String newPwd){
		try{
			Member member = super.getByField("username", mobile);
			if(member != null){
				super.update(member.getId(), "password", Digests.md5(newPwd));
				return 1;//修改成功
			}
			return -1;//会员不存在
		}catch(Exception e){
			logger.error("MemberService.updatePwd error", e);
			return 0;
		}
	}


	public MemberDTO findById(Long id){
		MemberDTO dto = new MemberDTO();
		Member member = getById(id);
		filled(dto, member);
		return dto;
	}

	//将member中信息填充到dto中
	public void filled(MemberDTO dto, Member member){
		//头像，昵称，签名，性别，城市，职业，邮箱，身份证，手机号，登录密码
		dto.setId(member.getId());
		dto.setNickname(member.getNickname());
		dto.setLogo(member.getLogo());
		dto.setSignature(member.getSignature());
		dto.setSex(member.getSex());
		dto.setCity(member.getCity());
		dto.setProfession(member.getProfession());
		dto.setEmail(member.getEmail());
		dto.setIdcard(member.getIdcard());
		dto.setMobile(member.getMobile());
		dto.setPassword(member.getPassword());
	}
}
